package account

import (
	"context"
	"strconv"
	"time"

	"user/internal/biz"
	"user/internal/svc"
	"user/internal/types"
	"user/models"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 用户登录
func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.LoginReq) (resp *types.LoginResp, err error) {
	// 1. validate username and password
	usersModel := models.NewUsersModel(l.svcCtx.SqlConn)
	user, err := usersModel.FindOneByUserNameAndPwd(l.ctx, req.Username, req.Password)
	if err != nil {
		l.Logger.Error("... 查询用户失败", err)
		return nil, biz.DBError
	}
	if user == nil {
		return nil, biz.UsernameAndPwdError
	}

	expire := l.svcCtx.Config.Auth.Expire
	// 2. generate token
	token, err := biz.GetJwtToken(l.svcCtx.Config.Auth.AccessSecret, time.Now().Unix(),
		expire,
		map[string]any{
			"userId": user.Id,
		})
	if err != nil {
		return nil, biz.TokenError
	}

	// 3. save token to redis, if operation already expired, delete token from redis
	err = l.svcCtx.RedisConn.SetexCtx(l.ctx, "token:"+token, strconv.FormatInt(user.Id, 10), int(expire))
	if err != nil {
		return nil, biz.RedisError
	}
	resp = &types.LoginResp{Token: token}
	return
}
